<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <script>
    /**
     * 2022年4月28日13:20:21
     * js 19
     * js二分查找
     */
    var arr = [0, 13, 21, 35, 46, 52, 68, 77, 89, 94];

    //非递归 
    function NotRecursiveSearch(arr, key) {
      start = 0;
      end = arr.length - 1;
      while (start <= end) {
        mid = parseInt((end + start) / 2)
        if (key == arr[mid]) {
          return mid;
        } else if (key > arr[mid]) {
          start = mid + 1
        } else {
          end = mid - 1
        }
      }
      return -1;
    }
    console.log(NotRecursiveSearch(arr, 21))

    //递归
    function recursiveSearch(arr, key, start, end) {
      if (start > end) {
        return -1;
      }
      start = start || 0
      end = end === undefined ? arr.length - 1 : end;
      var mid = parseInt((start + end) / 2)
      if (key === arr[mid]) {
        return mid;
      } else if (key < arr[mid]) {
        return recursiveSearch(arr, key, start, mid - 1)
      } else {
        return recursiveSearch(arr, key, mid + 1, end)
      }
    }
    console.log(recursiveSearch(arr, 21))
  </script>
</body>

</html>
